//
//  MenuTableViewController.m
//  CoolTennisBall
//
//  Created by 谢伟康 on 15/12/17.
//  Copyright © 2015年 CoolLang. All rights reserved.
//

#import "MenuTableViewController.h"
#import "CommunicationManager.h"
#import "MyTabbarViewController.h"
#import "MyNavigationViewController.h"
#import "MatchDeviceTipsViewController.h"
#import "FirmwareService.h"

NSString * const kMenuChangeDeviceNameNotification = @"MenuChangeDeviceNameNotification";

@interface MenuTableViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *deviceNameChangeLabel;
@property (weak, nonatomic) IBOutlet UILabel *batteryValueLabel;
@property (weak, nonatomic) IBOutlet UIImageView *batteryValueImageView;

@property (weak, nonatomic) IBOutlet UILabel *disconnectDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *changeDeviceDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *pairDeviceDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *remainBatteryDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *poweOffDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *rebootDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *firmwareDescriptionLabel;
@end

@implementation MenuTableViewController

#pragma mark - LifeViewCircle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureLocalization];
    [self configureTableView];
    [self configureBatteryUI];
}

#pragma mark - Localization

- (void)configureLocalization
{
    self.disconnectDescriptionLabel.text = NSLocalizedString(@"Disconnect Device", nil);
    self.deviceNameChangeLabel.text = NSLocalizedString(@"Setting Device Name", nil);
    self.pairDeviceDescriptionLabel.text = NSLocalizedString(@"Pair the Device", nil);
    self.remainBatteryDescriptionLabel.text = NSLocalizedString(@"Battery Usage", nil);
    self.poweOffDescriptionLabel.text = NSLocalizedString(@"Power off", nil);
    self.rebootDescriptionLabel.text = NSLocalizedString(@"Restart", nil);
    self.firmwareDescriptionLabel.text = NSLocalizedString(@"Firmware Update", nil);
}

#pragma mark - Private Method
- (void)configureTableView
{
    self.tableView.tableFooterView = [[UIView alloc] init];
}

- (void)showInputNameAlertView
{
    FUIAlertView *alert = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Setting Device Name", nil) message:NSLocalizedString(@"Menu.PleaseEnter", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"No", nil) otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
    alert.alertViewStyle = FUIAlertViewStylePlainTextInput;
    [alert customizeAppearance];
    FUITextField *textField = [alert textFieldAtIndex:0];
    textField.textFieldColor = [UIColor whiteColor];
    textField.cornerRadius = textField.bounds.size.width/2;
    alert.onOkAction = ^{
        
        if (!([textField.text length] > 0)) {
            return;
        }
        
        [[CommunicationManager shareInstance] performOperationType:OperationTypeChangeDeviceName object:textField.text completionBlock:^(BOOL success, id feedbackData) {
            if (success) {
                
                [BTHandler handleDeviceNameChangeData:feedbackData withCompetitionBlock:^(BOOL successful) {
                    if (successful) {
                        [MBProgressHUD showSuccessHudInView:MyTabbarView message:NSLocalizedString(@"Menu.ChangeName.Success", nil) afterDelay:1];
                        [[NSNotificationCenter defaultCenter] postNotificationName:kMenuChangeDeviceNameNotification object:nil userInfo:@{
                                                                                                                                           @"DeviceName": textField.text                                                              }];
                        
                    }else{
                        [MBProgressHUD showFailHudInView:MyTabbarView message:NSLocalizedString(@"Fail", nil) afterDelay:1];
                    }
                }];
                
            }else{
                [MBProgressHUD showFailHudInView:MyTabbarView message:NSLocalizedString(@"Fail", nil) afterDelay:1];
            }
        }];
    };
    [alert show];
}

- (void)showResetAlertView
{
    FUIAlertView *alert = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Restart", nil) message:NSLocalizedString(@"Confirm to restart?", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"No", nil) otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
    [alert customizeAppearance];
    alert.onOkAction = ^{
        [[CommunicationManager shareInstance] performOperationType:OperationTypeRestartDevice object:nil completionBlock:^(BOOL success, id feedbackData) {
            if (success) {
                [BTHandler handleRestartDeviceData:feedbackData withCompletion:^(BOOL successful) {
                    if (successful) {
                        [MBProgressHUD showSuccessHudInView:MyTabbarView message:NSLocalizedString(@"Success", nil) afterDelay:1];
                    }
                }];
            }
        }];
    };
    [alert show];
}

- (void)showCloseAlertView
{
    FUIAlertView *alert = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Power off", nil) message:NSLocalizedString(@"Confirm power off?", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"No", nil) otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
    [alert customizeAppearance];
    alert.onOkAction = ^{
        [[CommunicationManager shareInstance] performOperationType:OperationTypeCloseDevice object:nil completionBlock:^(BOOL success, id feedbackData) {
            if (success) {
                [BTHandler handleCloseDeviceData:feedbackData withCompletion:^(BOOL successful) {
                    if (successful) {
                        [MBProgressHUD showSuccessHudInView:MyTabbarView message:NSLocalizedString(@"Success", nil) afterDelay:1];
                    }
                }];
            }
        }];
    };
    [alert show];
}

- (void)showMatchDeviceAlertView
{
    MatchDeviceTipsViewController *matchVC = [[MatchDeviceTipsViewController alloc] init];
    [matchVC presentInParentViewController:self.tabBarController animationType:DetailViewControllerPresentAnimationTypePop];
}

- (void)configureBatteryUI
{
    __weak typeof(self) weakSelf = self;
    [[CommunicationManager shareInstance] performOperationType:OperationTypeBatteryRead object:nil completionBlock:^(BOOL success, id feedbackData) {
        if (success) {
            [BTHandler handleBatteryData:feedbackData withCompletion:^(NSInteger batteryValue) {
                if (batteryValue <= 20) {
                    weakSelf.batteryValueImageView.image = [UIImage imageNamed:@"sport_icon_redbattery"];
                    weakSelf.batteryValueLabel.textColor = [UIColor redColor];
                }else if (batteryValue <= 50){
                    weakSelf.batteryValueImageView.image = [UIImage imageNamed:@"sport_icon_orangebattery"];
                    weakSelf.batteryValueLabel.textColor = [UIColor orangeColor];
                }else if (batteryValue <= 100){
                    weakSelf.batteryValueImageView.image = [UIImage imageNamed:@"sport_icon_greenbattery"];
                    weakSelf.batteryValueLabel.textColor = kSelectedColor;
                }else if (batteryValue == 120){
                    weakSelf.batteryValueImageView.image = [UIImage imageNamed:@"sport_icon_fillbattery"];
                    weakSelf.batteryValueLabel.textColor = [UIColor clearColor];
                }
                weakSelf.batteryValueLabel.text = [NSString stringWithFormat:@"%ld%%",(long)batteryValue];
                weakSelf.batteryValueImageView.hidden = NO;
                weakSelf.batteryValueLabel.hidden = NO;
            }];
        }
    }];
}



#pragma mark - UITableViewDelegate

- (nullable NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 2) {
    
        return nil;
    }
    return indexPath;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.row) {
        case 0://断开连接
        {
            [[CommunicationManager shareInstance] disconnectThePeripheralWithCompletionBlock:^(BOOL success) {
                if (success) {
                    [CommunicationManager shareInstance].shouldRetryConnect = NO;
                }
            }];
        }
            break;
        case 1://修改设备名称
        {
            [self showInputNameAlertView];
        }
            break;
        case 2://配对设备
        {
            [self showMatchDeviceAlertView];
        }
            break;
        case 3://关闭设备
        {
            [self showCloseAlertView];
        }
            break;
        case 4://重启设备
        {
            [self showResetAlertView];
        }
            break;
        case 5://固件升级
        {
            [[FirmwareService sharedInstance] performRequestFirmwave:FirmwareAlertTypeNormal beginUpdateFirmwareBlock:^{
                if (self.delegate != nil && [self.delegate respondsToSelector:@selector(didSeleceMenu:atIndex:)]) {
                    [self.delegate didSeleceMenu:self atIndex:5];
                }
            } checkVersionCompletionBlock:nil];
        }
            break;
            
        default:
            break;
    }
    
    if (indexPath.row < 5) {
        if (_delegate != nil && [_delegate respondsToSelector:@selector(didSeleceMenu:atIndex:)]) {
            [_delegate didSeleceMenu:self atIndex:indexPath.row];
        }
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.highlightedTextColor = cell.textLabel.textColor;
    
    UIView *selectionView = [[UIView alloc] initWithFrame:CGRectZero];
    selectionView.backgroundColor = [UIColor colorWithHex:0x000000 alpha:0.2];
    cell.selectedBackgroundView = selectionView;
    
    if (indexPath.row == 3) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
}

@end
